/**
 * Project 67th
 */


#include "TcpConnection.h"
#include <sstream>
using std::ostringstream;

/**
 * TcpConnection implementation
 */


/**
 * @param fd
 */
TcpConnection::TcpConnection(int fd) 
: _sockIO(fd)
, _sock(fd)
, _localAddr(getLocalAddr())
, _peerAddr(getPeerAddr())
{

}

TcpConnection::~TcpConnection() {

}

/**
 * @return string
 */
string TcpConnection::receive() {
    char buff[65535] = {0};
    _sockIO.readLine(buff,sizeof(buff));
    return string(buff);
}

/**
 * @param msg
 * @return void
 */
void TcpConnection::send(const string & msg) {
    _sockIO.writen(msg.c_str(),msg.size());
}


string TcpConnection::toString()
{
    ostringstream oss;
    oss << _localAddr.getIp() << ":"
        << _localAddr.getPort() << "------>"
        << _peerAddr.getIp() << ":"
        << _peerAddr.getPort();
    return oss.str();
}

InetAddress TcpConnection::getLocalAddr()
{
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);

    //获取本端的地址信息
    int ret = getsockname(_sock.getFd(),
                          (struct sockaddr*)&addr,
                          &len);
    if(ret < 0)
    {
        perror("getsockname");
    }

    return InetAddress(addr);
}

InetAddress TcpConnection::getPeerAddr()
{
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);

    //获取对端的地址信息
    int ret = getpeername(_sock.getFd(),
                          (struct sockaddr*)&addr,
                          &len);
    if(ret < 0)
    {
        perror("getsockname");
    }

    return InetAddress(addr);
}
